package org.example.rpc;

import org.apache.pekko.actor.AbstractActor;
import org.apache.pekko.actor.ActorRef;
import org.apache.pekko.actor.Props;
import org.example.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @className: RpcActor
 * @Description: 持有一个 T ，在 RpcActor 的 hanndle 方法中，反射的调用 T 中的方法。
 * @Author: wangyifei
 * @Date: 2025/3/13 11:31
 */
public class RpcActor extends AbstractActor{
    private static Logger logger = LoggerFactory.getLogger(RpcActor.class);
    private Object target ;
    private ActorRef actorRef ;
    public RpcActor(Object target) {
        this.target = target;
    }
    public static Props props(Object target){
        return Props.create(RpcActor.class , ()-> new RpcActor(target)) ;
    }
    @Override
    public Receive createReceive() {
        return receiveBuilder().match(Message.class , this::messageHandler).matchAny(msg -> {
            System.out.println(msg);
        }).build();
    }

    private void messageHandler(Message p) {
        String s = getSender().path().toString();
        String method = p.getMessage().toString();
        Class[] parameter = p.getParemeterClass();
        try {
            Method method1 = target.getClass().getMethod(method, parameter);
            method1.invoke(target , p.getParameters());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
